package com.example.passport.controller;

import com.example.common.dto.JsonResult;
import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.interceptor.UserContext;
import com.example.passport.dto.*;
import com.example.passport.entity.User;
import com.example.passport.entity.UserRole;
import com.example.passport.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@Api(tags = "用户角色管理")
@RestController
@CrossOrigin
@RequestMapping("/passport/userRole")
public class UserRoleController {

    @Resource
    UserRoleService userRoleService;

    @ApiOperation("添加用户角色")
    @PostMapping("/create")
    public JsonResult<String> create(@Valid UserRoleCreateDto userRoleCreateDto) {
        User user = UserContext.getUser();
        UserRole userRole = new UserRole();
        BeanUtils.copyProperties(userRoleCreateDto,userRole);
        userRole.setTenantId(user.getTenantId());
        userRoleService.createUserRole(userRole);
        return new JsonResult<>(true,"添加成功");
    }

    @ApiOperation("列出用户角色")
    @GetMapping("/list")
    public JsonResult<ListDto<UserRoleDto>> list(Long roleId, Pagination pagination){
        User user = UserContext.getUser();
        UserRoleDto userRoleDto = UserRoleDto.builder().roleId(roleId).tenantId(user.getTenantId()).build();
        return new JsonResult<>(userRoleService.list(userRoleDto,pagination));
    }

    @ApiOperation("修改用户角色")
    @PostMapping("/update")
    public JsonResult<String> update(@Valid UserRoleSearchDto userRoleSearchDto){
        User user = UserContext.getUser();
        UserRole userRole = new UserRole();
        BeanUtils.copyProperties(userRoleSearchDto,userRole);
        userRole.setTenantId(user.getTenantId());
        userRoleService.update(userRole);
        return new JsonResult<>(true,"添加成功");
    }

    @ApiOperation("删除用户角色")
    @PostMapping("/delete")
    public JsonResult<String> delete(Long id){
        User user = UserContext.getUser();
        UserRole userRole = UserRole.builder().id(id).tenantId(user.getTenantId()).build();
        userRoleService.delete(userRole);
        return new JsonResult<>(true,"删除成功");
    }
}
